package com.gexiaobao.pigeon.ui.fragment.mine.banking

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.setFragmentResultListener
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.bean.AccountUserInfo
import com.gexiaobao.pigeon.app.model.bean.QueryBalanceResponse
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.FragmentMineBankingBinding
import com.gexiaobao.pigeon.ui.dialog.AlertDialog
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.viewmodel.MineBankingViewModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 15:20
 * @Describe    : 我的金融
 */
class FragmentMineBanking : BaseFragment<MineBankingViewModel, FragmentMineBankingBinding>() {

    private var mQueryBalance: QueryBalanceResponse? = null
    private var mAccountUserInfo: AccountUserInfo? = null
    private var mType: Int = 0
    private var moneyVisibility = true
    private var mGebiCnt: Int = 0

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewmodel = mViewModel

        mDatabind.swipeRefreshLayout.init {
            mViewModel.getUserMemberInfo()
            lazyLoadData()
        }

        setFragmentResultListener("RechargeIsOk") { _, bundle ->
            if (bundle.getBoolean("isOK")) {
                lazyLoadData()
            }
        }
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        showLoadingAntiShake(getString(R.string.loading))
        mViewModel.queryBalance()
    }

    override fun onResume() {
        super.onResume()
        mType = arguments?.getInt(Constant.INTO_TYPE)!!
        showLoadingAntiShake(getString(R.string.loading))
        mViewModel.getUserMemberInfo()
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.mineAccountSee,
            mDatabind.headerBgClose,
            mDatabind.mineAccountCard,
            mDatabind.mineAccountTransaction,
            mDatabind.mineAccountUnbindPhone,
            mDatabind.mineAccountInvestMoney,
            mDatabind.mineAccountWithdraw,
            mDatabind.mineAccountTransfer,
            mDatabind.refreshAccountInfo,
            mDatabind.mineAccountUpdatePwd,
            mDatabind.mineAccountResetPwd,
            mDatabind.tvInterestSettlement
        ) { it ->
            when (it) {
                mDatabind.tvInterestSettlement -> {
                    showLoading(getString(R.string.loading))
                    mViewModel.settlement()
                }

                mDatabind.mineAccountSee -> {
                    moneyVisibility = !moneyVisibility
                    mQueryBalance?.let { it1 -> moneyVisibility(it1) }
                    KvUtils.encode(Constant.MONEY_VISIBILITY, moneyVisibility)
                }

                mDatabind.headerBgClose -> {
                    if (mType == 1) {
                        nav().navigateUp()
                    } else {
                        nav().popBackStack(R.id.fragment_account_setting_process, true)
                    }
                }

                mDatabind.mineAccountCard -> {
                    jumpToNextPage(1)
                }

                mDatabind.mineAccountTransaction -> {
                    jumpToNextPage(2)
                }

                mDatabind.mineAccountUnbindPhone -> {
                    jumpToNextPage(3)
                }

                mDatabind.mineAccountInvestMoney -> {//充值
                    if (mAccountUserInfo!!.isIdentityChecked
                        && mAccountUserInfo!!.isSignContract
                        && mAccountUserInfo!!.isPhoneChecked
                        && mAccountUserInfo!!.isSetPayPwd
                        && mAccountUserInfo!!.isBindBank
                    ) {
                        nav().navigateAction(R.id.action_to_account_recharge)
                    } else {
                        context?.let {
                            AlertDialog(it).builder().setMsg(getString(R.string.mine_account_activity_err_alert_msg))
                                .setPositiveButton(getString(R.string.ok)) {
                                    nav().navigateAction(R.id.action_to_account_setting_process, Bundle().apply {
                                        putString(Constant.INTO_TYPE, "mineBank")
                                    })
                                }.setCancelable(false).show()
                        }
                    }
//                    jumpToNextPage(4)
                }

                mDatabind.mineAccountWithdraw -> {//提现
                    if (mAccountUserInfo!!.isIdentityChecked
                        && mAccountUserInfo!!.isSignContract
                        && mAccountUserInfo!!.isPhoneChecked
                        && mAccountUserInfo!!.isSetPayPwd
                        && mAccountUserInfo!!.isBindBank
                    ) {
                        nav().navigateAction(R.id.action_to_account_withdrawal, Bundle().apply {
                            putParcelable(Constant.DATA_BEAN, mQueryBalance)
                        })
                    } else {
                        context?.let {
                            AlertDialog(it).builder().setMsg(getString(R.string.mine_account_activity_err_alert_msg))
                                .setPositiveButton(getString(R.string.ok)) {
                                    nav().navigateAction(R.id.action_to_account_setting_process, Bundle().apply {
                                        putString(Constant.INTO_TYPE, "mineBank")
                                    })
                                }.setCancelable(false).show()
                        }
                    }
//                    jumpToNextPage(5)
                }

                mDatabind.mineAccountTransfer -> {
                    jumpToNextPage(6)
                }

                mDatabind.refreshAccountInfo -> {
                    showLoadingAntiShake(getString(R.string.loading))
                    mViewModel.queryBalance()
                }

                mDatabind.mineAccountUpdatePwd -> {
                    nav().navigateAction(R.id.action_to_fragment_set_payment_pwd, Bundle().apply {
                        putInt("type", 2)//修改密码
                    })
                }

                mDatabind.mineAccountResetPwd -> {
                    nav().navigateAction(R.id.action_to_fragment_set_payment_pwd, Bundle().apply {
                        putInt("type", 3)//重置密码
                    })
                }
            }
        }
    }

    private fun jumpToNextPage(type: Int) {
        try {
            if (mAccountUserInfo!!.isIdentityChecked
                && mAccountUserInfo!!.isSignContract
                && mAccountUserInfo!!.isPhoneChecked
                && mAccountUserInfo!!.isSetPayPwd
            ) {
                when (type) {
                    1 -> {
                        nav().navigateAction(R.id.action_to_bank_card)
                    }

                    2 -> {
                        nav().navigateAction(R.id.action_to_bank_transaction_record)
                    }

                    3 -> {
                        nav().navigateAction(R.id.action_to_account_unbind_phone, Bundle().apply {
                            putString("mobile", mAccountUserInfo?.phone)
                        })
                    }

//                    4 -> {
//                        nav().navigateAction(R.id.action_to_account_recharge)
//                    }

//                    5 -> {
//                        nav().navigateAction(R.id.action_to_account_withdrawal, Bundle().apply {
//                            putParcelable(Constant.DATA_BEAN, mQueryBalance)
//                        })
//                    }

                    6 -> {
                        nav().navigateAction(R.id.action_to_account_transfer, Bundle().apply {
                            putParcelable(Constant.DATA_BEAN, mQueryBalance)
                        })
                    }
                }
            } else {
                context?.let {
                    AlertDialog(it).builder().setMsg(getString(R.string.mine_account_activity_err_alert_msg))
                        .setPositiveButton(getString(R.string.ok)) {
                            nav().navigateAction(R.id.action_to_account_setting_process, Bundle().apply {
                                putString(Constant.INTO_TYPE, "mineBank")
                            })
                        }.setCancelable(false).show()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            RxToast.showToast(getString(R.string.mine_account_activity_err_could))
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.tlementResult.observe(viewLifecycleOwner) {
            mViewModel.queryBalance()
        }
        mViewModel.accountUserInfoResult.observe(viewLifecycleOwner) { resultState ->
            dismissLoadingAntiShake()
            parseState(resultState, {
                dismissRefresh()
                mAccountUserInfo = it
//                if (!it.isIdentityChecked || !it.isSignContract || !it.isPhoneChecked || !it.isSetPayPwd || !it.isBindBank) {
//                    showDialogSign()
//                }
            }, {
                RxToast.showToast(it.msg)
            })
        }

        mViewModel.queryBalanceResult.observe(viewLifecycleOwner) { resultState ->
            dismissRefresh()
            dismissLoadingAntiShake()
            parseState(resultState, {
                moneyVisibility = KvUtils.decodeBooleanTure(Constant.MONEY_VISIBILITY, true)
                mQueryBalance = it
                mDatabind.data = it
                moneyVisibility(mQueryBalance!!)
            }, {
                RxToast.showToast(it.msg)
            })
        }
    }

    private fun showDialogSign() {
        val dialog = RxDialogDefault(context)
        dialog.setTitle("你还没有认证成功，继续认证?")
        dialog.setSureListener {
            dialog.dismiss()
            nav().navigateAction(R.id.action_to_account_setting_process, Bundle().apply {
                putString(Constant.INTO_TYPE, "mineBank")
            })
        }
        dialog.setCancelListener {
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun dismissRefresh() {
        if (mDatabind.swipeRefreshLayout.isRefreshing) {
            mDatabind.swipeRefreshLayout.isRefreshing = false
        }
    }

    @SuppressLint("SetTextI18n")
    private fun moneyVisibility(it: QueryBalanceResponse) {
        if (moneyVisibility) {
            mGebiCnt = it.gebiCnt
            mDatabind.tvMineBankingGebi.text = mGebiCnt.toString()
            mDatabind.mineAccountAllAmount.text = "" + Util.makeDoubleToThousand(99999999999.00 / Util.tlUnit)
            mDatabind.tvMineBalanceInterest.text = "" + Util.makeDoubleToThousand(99999999999.00 / Util.tlUnit)
            mDatabind.mineAccountFreezenAmount.text = "" + Util.makeDoubleToThousand(9999999999.00 / Util.tlUnit)
            mDatabind.mineAccountAllAmount.text = Util.makeDoubleToThousand(SettingUtil.div(it.allAmount, 100.00, 2)).toString()
            mDatabind.tvMineBalanceInterest.text = "利息: " + Util.makeDoubleToThousand(SettingUtil.div(it.interest, 100.00, 2)).toString()
            mDatabind.mineAccountFreeAmount.text =
                Util.makeDoubleToThousand(SettingUtil.div(it.allAmount - it.freezenAmount, 100.00, 2)).toString()
            mDatabind.mineAccountFreezenAmount.text = Util.makeDoubleToThousand(SettingUtil.div(it.freezenAmount, 100.00, 2)).toString()
            /**
             * 计算可用余额
             * 1、判断账户总额是否为0。为0时则不计算
             * 2、（账户总额-冻结余额）/账户总额 = 可用余额的百分比
             * 3、可用余额的百分比*100得到最后的值
             */
            if (it.allAmount != 0.0) {
                val progressCanUse = (Util.div(Util.sub(it.allAmount, it.freezenAmount).toDouble(), it.allAmount, 2) * 100).toFloat()
                mDatabind.mineAccountFreeAmountCp.setProgressWithAnimation(progressCanUse, 800)
            }
            /**
             * 计算冻结余额
             * 1、判断冻结余额是否为0，为0时则不判断
             */
            if (it.freezenAmount != 0.0) {
                val progressFreeze = (Util.div(it.freezenAmount, it.allAmount, 2) * 100).toFloat()
                mDatabind.mineAccountFreezenAmountCp.setProgressWithAnimation(progressFreeze, 800)
                mDatabind.mineAccountFreezenAmountCp.setProgressWithAnimation(progressFreeze, 800)
                mDatabind.mineAccountGebi.setProgressWithAnimation(progressFreeze, 800)
            }
            mDatabind.mineAccountSee.background = context?.let { it1 -> ContextCompat.getDrawable(it1, R.mipmap.ic_visibility_white_36dp) }
        } else {
            mDatabind.tvMineBankingGebi.text = "**"
            mDatabind.mineAccountAllAmount.text = "**"
            mDatabind.mineAccountFreezenAmount.text = "**"
            mDatabind.tvMineBankingGebi.text = "**"
            mDatabind.mineAccountFreeAmount.text = "**"
            mDatabind.mineAccountFreeAmountCp.setProgressWithAnimation(0f, 800)
            mDatabind.mineAccountFreezenAmountCp.setProgressWithAnimation(0f, 800)
            mDatabind.mineAccountGebi.setProgressWithAnimation(0f, 800)
            mDatabind.mineAccountSee.background = context?.let { it1 -> ContextCompat.getDrawable(it1, R.mipmap.ic_visibility_off_white_36dp) }
        }
    }
}